home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / wsgiref / handlers.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-11-11  |  15.8 KB  |  461 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Base classes for server/gateway implementations'''
  5. from types import StringType
  6. from util import FileWrapper, guess_scheme, is_hop_by_hop
  7. from headers import Headers
  8. import sys
  9. import os
  10. import time
  11. __all__ = [
  12.     'BaseHandler',
  13.     'SimpleHandler',
  14.     'BaseCGIHandler',
  15.     'CGIHandler']
  16.  
  17. try:
  18.     dict
  19. except NameError:
  20.     
  21.     def dict(items):
  22.         d = { }
  23.         for k, v in items:
  24.             d[k] = v
  25.         
  26.         return d
  27.  
  28.  
  29. _weekdayname = [
  30.     'Mon',
  31.     'Tue',
  32.     'Wed',
  33.     'Thu',
  34.     'Fri',
  35.     'Sat',
  36.     'Sun']
  37. _monthname = [
  38.     None,
  39.     'Jan',
  40.     'Feb',
  41.     'Mar',
  42.     'Apr',
  43.     'May',
  44.     'Jun',
  45.     'Jul',
  46.     'Aug',
  47.     'Sep',
  48.     'Oct',
  49.     'Nov',
  50.     'Dec']
  51.  
  52. def format_date_time(timestamp):
  53.     (year, month, day, hh, mm, ss, wd, y, z) = time.gmtime(timestamp)
  54.     return '%s, %02d %3s %4d %02d:%02d:%02d GMT' % (_weekdayname[wd], day, _monthname[month], year, hh, mm, ss)
  55.  
  56.  
  57. class BaseHandler:
  58.     '''Manage the invocation of a WSGI application'''
  59.     wsgi_version = (1, 0)
  60.     wsgi_multithread = True
  61.     wsgi_multiprocess = True
  62.     wsgi_run_once = False
  63.     origin_server = True
  64.     http_version = '1.0'
  65.     server_software = None
  66.     os_environ = dict(os.environ.items())
  67.     wsgi_file_wrapper = FileWrapper
  68.     headers_class = Headers
  69.     traceback_limit = None
  70.     error_status = '500 Dude, this is whack!'
  71.     error_headers = [
  72.         ('Content-Type', 'text/plain')]
  73.     error_body = 'A server error occurred.  Please contact the administrator.'
  74.     status = None
  75.     result = None
  76.     headers_sent = False
  77.     headers = None
  78.     bytes_sent = 0
  79.     
  80.     def run(self, application):
  81.         '''Invoke the application'''
  82.         
  83.         try:
  84.             self.setup_environ()
  85.             self.result = application(self.environ, self.start_response)
  86.             self.finish_response()
  87.         except:
  88.             
  89.             try:
  90.                 self.handle_error()
  91.             self.close()
  92.             raise 
  93.  
  94.  
  95.  
  96.     
  97.     def setup_environ(self):
  98.         '''Set up the environment for one request'''
  99.         env = self.environ = self.os_environ.copy()
  100.         self.add_cgi_vars()
  101.         env['wsgi.input'] = self.get_stdin()
  102.         env['wsgi.errors'] = self.get_stderr()
  103.         env['wsgi.version'] = self.wsgi_version
  104.         env['wsgi.run_once'] = self.wsgi_run_once
  105.         env['wsgi.url_scheme'] = self.get_scheme()
  106.         env['wsgi.multithread'] = self.wsgi_multithread
  107.         env['wsgi.multiprocess'] = self.wsgi_multiprocess
  108.         if self.wsgi_file_wrapper is not None:
  109.             env['wsgi.file_wrapper'] = self.wsgi_file_wrapper
  110.         
  111.         if self.origin_server and self.server_software:
  112.             env.setdefault('SERVER_SOFTWARE', self.server_software)
  113.         
  114.  
  115.     
  116.     def finish_response(self):
  117.         """Send any iterable data, then close self and the iterable
  118.  
  119.         Subclasses intended for use in asynchronous servers will
  120.         want to redefine this method, such that it sets up callbacks
  121.         in the event loop to iterate over the data, and to call
  122.         'self.close()' once the response is finished.
  123.         """
  124.         if not self.result_is_file() or not self.sendfile():
  125.             for data in self.result:
  126.                 self.write(data)
  127.             
  128.             self.finish_content()
  129.         
  130.         self.close()
  131.  
  132.     
  133.     def get_scheme(self):
  134.         '''Return the URL scheme being used'''
  135.         return guess_scheme(self.environ)
  136.  
  137.     
  138.     def set_content_length(self):
  139.         '''Compute Content-Length or switch to chunked encoding if possible'''
  140.         
  141.         try:
  142.             blocks = len(self.result)
  143.         except (TypeError, AttributeError, NotImplementedError):
  144.             pass
  145.  
  146.         if blocks == 1:
  147.             self.headers['Content-Length'] = str(self.bytes_sent)
  148.             return None
  149.  
  150.     
  151.     def cleanup_headers(self):
  152.         '''Make any necessary header changes or defaults
  153.  
  154.         Subclasses can extend this to add other defaults.
  155.         '''
  156.         if not self.headers.has_key('Content-Length'):
  157.             self.set_content_length()
  158.         
  159.  
  160.     
  161.     def start_response(self, status, headers, exc_info = None):
  162.         """'start_response()' callable as specified by PEP 333"""
  163.         if exc_info:
  164.             
  165.             try:
  166.                 if self.headers_sent:
  167.                     raise exc_info[0], exc_info[1], exc_info[2]
  168.                 self.headers_sent
  169.             finally:
  170.                 exc_info = None
  171.  
  172.         elif self.headers is not None:
  173.             raise AssertionError('Headers already set!')
  174.         
  175.         if not type(status) is StringType:
  176.             raise AssertionError, 'Status must be a string'
  177.         if not len(status) >= 4:
  178.             raise AssertionError, 'Status must be at least 4 characters'
  179.         if not int(status[:3]):
  180.             raise AssertionError, 'Status message must begin w/3-digit code'
  181.         if not status[3] == ' ':
  182.             raise AssertionError, 'Status message must have a space after code'
  183.         for name, val in headers:
  184.             if not type(name) is StringType:
  185.                 raise AssertionError, 'Header names must be strings'
  186.             if not type(val) is StringType:
  187.                 raise AssertionError, 'Header values must be strings'
  188.             if not not is_hop_by_hop(name):
  189.                 raise AssertionError, 'Hop-by-hop headers not allowed'
  190.         
  191.         self.status = status
  192.         self.headers = self.headers_class(headers)
  193.         return self.write
  194.  
  195.     
  196.     def send_preamble(self):
  197.         '''Transmit version/status/date/server, via self._write()'''
  198.         if self.origin_server:
  199.             if self.client_is_modern():
  200.                 self._write('HTTP/%s %s\r\n' % (self.http_version, self.status))
  201.                 if not self.headers.has_key('Date'):
  202.                     self._write('Date: %s\r\n' % format_date_time(time.time()))
  203.                 
  204.                 if self.server_software and not self.headers.has_key('Server'):
  205.                     self._write('Server: %s\r\n' % self.server_software)
  206.                 
  207.             
  208.         else:
  209.             self._write('Status: %s\r\n' % self.status)
  210.  
  211.     
  212.     def write(self, data):
  213.         """'write()' callable as specified by PEP 333"""
  214.         if not type(data) is StringType:
  215.             raise AssertionError, 'write() argument must be string'
  216.         if not self.status:
  217.             raise AssertionError('write() before start_response()')
  218.         self.status
  219.         self._write(data)
  220.         self._flush()
  221.  
  222.     
  223.     def sendfile(self):
  224.         """Platform-specific file transmission
  225.  
  226.         Override this method in subclasses to support platform-specific
  227.         file transmission.  It is only called if the application's
  228.         return iterable ('self.result') is an instance of
  229.         'self.wsgi_file_wrapper'.
  230.  
  231.         This method should return a true value if it was able to actually
  232.         transmit the wrapped file-like object using a platform-specific
  233.         approach.  It should return a false value if normal iteration
  234.         should be used instead.  An exception can be raised to indicate
  235.         that transmission was attempted, but failed.
  236.  
  237.         NOTE: this method should call 'self.send_headers()' if
  238.         'self.headers_sent' is false and it is going to attempt direct
  239.         transmission of the file.
  240.         """
  241.         return False
  242.  
  243.     
  244.     def finish_content(self):
  245.         '''Ensure headers and content have both been sent'''
  246.         if not self.headers_sent:
  247.             self.headers['Content-Length'] = '0'
  248.             self.send_headers()
  249.         
  250.  
  251.     
  252.     def close(self):
  253.         '''Close the iterable (if needed) and reset all instance vars
  254.  
  255.         Subclasses may want to also drop the client connection.
  256.         '''
  257.         
  258.         try:
  259.             if hasattr(self.result, 'close'):
  260.                 self.result.close()
  261.         finally:
  262.             self.result = None
  263.             self.headers = None
  264.             self.status = None
  265.             self.environ = None
  266.             self.bytes_sent = 0
  267.             self.headers_sent = False
  268.  
  269.  
  270.     
  271.     def send_headers(self):
  272.         '''Transmit headers to the client, via self._write()'''
  273.         self.cleanup_headers()
  274.         self.headers_sent = True
  275.         if not (self.origin_server) or self.client_is_modern():
  276.             self.send_preamble()
  277.             self._write(str(self.headers))
  278.         
  279.  
  280.     
  281.     def result_is_file(self):
  282.         """True if 'self.result' is an instance of 'self.wsgi_file_wrapper'"""
  283.         wrapper = self.wsgi_file_wrapper
  284.         if wrapper is not None:
  285.             pass
  286.         return isinstance(self.result, wrapper)
  287.  
  288.     
  289.     def client_is_modern(self):
  290.         '''True if client can accept status and headers'''
  291.         return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
  292.  
  293.     
  294.     def log_exception(self, exc_info):
  295.         """Log the 'exc_info' tuple in the server log
  296.  
  297.         Subclasses may override to retarget the output or change its format.
  298.         """
  299.         
  300.         try:
  301.             print_exception = print_exception
  302.             import traceback
  303.             stderr = self.get_stderr()
  304.             print_exception(exc_info[0], exc_info[1], exc_info[2], self.traceback_limit, stderr)
  305.             stderr.flush()
  306.         finally:
  307.             exc_info = None
  308.  
  309.  
  310.     
  311.     def handle_error(self):
  312.         '''Log current error, and send error output to client if possible'''
  313.         self.log_exception(sys.exc_info())
  314.         if not self.headers_sent:
  315.             self.result = self.error_output(self.environ, self.start_response)
  316.             self.finish_response()
  317.         
  318.  
  319.     
  320.     def error_output(self, environ, start_response):
  321.         """WSGI mini-app to create error output
  322.  
  323.         By default, this just uses the 'error_status', 'error_headers',
  324.         and 'error_body' attributes to generate an output page.  It can
  325.         be overridden in a subclass to dynamically generate diagnostics,
  326.         choose an appropriate message for the user's preferred language, etc.
  327.  
  328.         Note, however, that it's not recommended from a security perspective to
  329.         spit out diagnostics to any old user; ideally, you should have to do
  330.         something special to enable diagnostic output, which is why we don't
  331.         include any here!
  332.         """
  333.         start_response(self.error_status, self.error_headers[:], sys.exc_info())
  334.         return [
  335.             self.error_body]
  336.  
  337.     
  338.     def _write(self, data):
  339.         """Override in subclass to buffer data for send to client
  340.  
  341.         It's okay if this method actually transmits the data; BaseHandler
  342.         just separates write and flush operations for greater efficiency
  343.         when the underlying system actually has such a distinction.
  344.         """
  345.         raise NotImplementedError
  346.  
  347.     
  348.     def _flush(self):
  349.         """Override in subclass to force sending of recent '_write()' calls
  350.  
  351.         It's okay if this method is a no-op (i.e., if '_write()' actually
  352.         sends the data.
  353.         """
  354.         raise NotImplementedError
  355.  
  356.     
  357.     def get_stdin(self):
  358.         """Override in subclass to return suitable 'wsgi.input'"""
  359.         raise NotImplementedError
  360.  
  361.     
  362.     def get_stderr(self):
  363.         """Override in subclass to return suitable 'wsgi.errors'"""
  364.         raise NotImplementedError
  365.  
  366.     
  367.     def add_cgi_vars(self):
  368.         """Override in subclass to insert CGI variables in 'self.environ'"""
  369.         raise NotImplementedError
  370.  
  371.  
  372.  
  373. class SimpleHandler(BaseHandler):
  374.     """Handler that's just initialized with streams, environment, etc.
  375.  
  376.     This handler subclass is intended for synchronous HTTP/1.0 origin servers,
  377.     and handles sending the entire response output, given the correct inputs.
  378.  
  379.     Usage::
  380.  
  381.         handler = SimpleHandler(
  382.             inp,out,err,env, multithread=False, multiprocess=True
  383.         )
  384.         handler.run(app)"""
  385.     
  386.     def __init__(self, stdin, stdout, stderr, environ, multithread = True, multiprocess = False):
  387.         self.stdin = stdin
  388.         self.stdout = stdout
  389.         self.stderr = stderr
  390.         self.base_env = environ
  391.         self.wsgi_multithread = multithread
  392.         self.wsgi_multiprocess = multiprocess
  393.  
  394.     
  395.     def get_stdin(self):
  396.         return self.stdin
  397.  
  398.     
  399.     def get_stderr(self):
  400.         return self.stderr
  401.  
  402.     
  403.     def add_cgi_vars(self):
  404.         self.environ.update(self.base_env)
  405.  
  406.     
  407.     def _write(self, data):
  408.         self.stdout.write(data)
  409.         self._write = self.stdout.write
  410.  
  411.     
  412.     def _flush(self):
  413.         self.stdout.flush()
  414.         self._flush = self.stdout.flush
  415.  
  416.  
  417.  
  418. class BaseCGIHandler(SimpleHandler):
  419.     """CGI-like systems using input/output/error streams and environ mapping
  420.  
  421.     Usage::
  422.  
  423.         handler = BaseCGIHandler(inp,out,err,env)
  424.         handler.run(app)
  425.  
  426.     This handler class is useful for gateway protocols like ReadyExec and
  427.     FastCGI, that have usable input/output/error streams and an environment
  428.     mapping.  It's also the base class for CGIHandler, which just uses
  429.     sys.stdin, os.environ, and so on.
  430.  
  431.     The constructor also takes keyword arguments 'multithread' and
  432.     'multiprocess' (defaulting to 'True' and 'False' respectively) to control
  433.     the configuration sent to the application.  It sets 'origin_server' to
  434.     False (to enable CGI-like output), and assumes that 'wsgi.run_once' is
  435.     False.
  436.     """
  437.     origin_server = False
  438.  
  439.  
  440. class CGIHandler(BaseCGIHandler):
  441.     """CGI-based invocation via sys.stdin/stdout/stderr and os.environ
  442.  
  443.     Usage::
  444.  
  445.         CGIHandler().run(app)
  446.  
  447.     The difference between this class and BaseCGIHandler is that it always
  448.     uses 'wsgi.run_once' of 'True', 'wsgi.multithread' of 'False', and
  449.     'wsgi.multiprocess' of 'True'.  It does not take any initialization
  450.     parameters, but always uses 'sys.stdin', 'os.environ', and friends.
  451.  
  452.     If you need to override any of these parameters, use BaseCGIHandler
  453.     instead.
  454.     """
  455.     wsgi_run_once = True
  456.     
  457.     def __init__(self):
  458.         BaseCGIHandler.__init__(self, sys.stdin, sys.stdout, sys.stderr, dict(os.environ.items()), multithread = False, multiprocess = True)
  459.  
  460.  
  461.